package com.showcase.cloud.gateway.controller;

import com.showcase.cloud.gateway.utils.CommonConstant;
import com.sun.showcase.pojo.Result;
import com.sun.showcase.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@RestController
@RequestMapping(value="/auth")
public class AuthController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.header}")
    private String tokenHeader;

    @RequestMapping(value = "/check_token")
    public Mono<Result<String>> checkToken(ServerHttpRequest request) {
        Result<String> res = new Result<String>();
        List<String> hs = request.getHeaders().get(CommonConstant.CLIENT_AUTH_HEAD);
        if(hs == null || hs.size()==0){
            res.setSuccess(false);
            res.setMsg("无效token");
            res.setCode("10001");
            return Mono.just(res);
        }
        String un = jwtTokenUtil.getUserNameFromToken(hs.get(0));
        if(un == null){
            res.setSuccess(false);
            res.setMsg("无效token");
            res.setCode("10001");
            return Mono.just(res);
        }
        res.setSuccess(true);
        res.setData(un);
        res.setCode("0");
        return Mono.just(res);
    }
    @RequestMapping(value = "/auth/refresh")
    public Mono<Result<String>> refreshToken(ServerHttpRequest request) {
        Result<String> res = new Result<String>();
        List<String> hs = request.getHeaders().get(CommonConstant.CLIENT_AUTH_HEAD);
        if(hs == null || hs.size()==0){
            res.setSuccess(false);
            res.setMsg("无效token");
            res.setCode("10001");
        }
        String un = jwtTokenUtil.getUserNameFromToken(hs.get(0));
        if(un == null){
            res.setSuccess(false);
            res.setMsg("无效token");
            res.setCode("10001");
        }
        un = jwtTokenUtil.refreshHeadToken(hs.get(0));
        res.setSuccess(true);
        res.setData(un);
        res.setCode("0");
        return Mono.just(res);
    }
}
